<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      {{#each columns}}
      {{#if isQuery}}
      {{#if (hbs_eq htmlType "input")}}
      <el-form-item label="{{columnComment}}" prop="{{tsField}}">
        <el-input
          v-model="queryParams.{{tsField}}"
          placeholder="请输入{{columnComment}}"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      {{/if}}
      {{#if (hbs_and (hbs_or (hbs_eq htmlType "select") (hbs_eq htmlType "radio")) dictType)}}
      <el-form-item label="{{columnComment}}" prop="{{tsField}}">
        <el-select v-model="queryParams.{{tsField}}" placeholder="请选择{{columnComment}}" clearable>
          <el-option
            v-for="dict in {{dictType}}"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      {{/if}}
      {{#if (hbs_and (hbs_eq htmlType "datetime") (hbs_not (hbs_eq queryType "BETWEEN")))}}
      <el-form-item label="{{columnComment}}" prop="{{tsField}}">
        <el-date-picker clearable
          v-model="queryParams.{{tsField}}"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择{{columnComment}}">
        </el-date-picker>
      </el-form-item>
      {{/if}}
      {{#if (hbs_and (hbs_eq htmlType "datetime") (hbs_eq queryType "BETWEEN"))}}
      <el-form-item label="{{columnComment}}" style="width: 308px">
        <el-date-picker
          v-model="daterange{{AttrName}}"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      {{/if}}
      {{/if}}
      {{/each}}
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['{{moduleName}}:{{businessName}}:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['{{moduleName}}:{{businessName}}:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['{{moduleName}}:{{businessName}}:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['{{moduleName}}:{{businessName}}:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="{{businessName}}List" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      {{#each columns}}
      {{#if isList}}
      {{#if (hbs_eq htmlType "datetime")}}
      <el-table-column label="{{columnComment}}" align="center" prop="{{tsField}}" width="180">
        <template #default="scope">
          <span>{{ "{{" }} parseTime(scope.row.{{tsField}}, '{y}-{m}-{d}') {{ "}}" }}</span>
        </template>
      </el-table-column>
      {{else if (hbs_eq htmlType "imageUpload")}}
      <el-table-column label="{{columnComment}}" align="center" prop="{{tsField}}" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.{{tsField}}" :width="50" :height="50"/>
        </template>
      </el-table-column>
      {{else if dictType}}
      <el-table-column label="{{columnComment}}" align="center" prop="{{tsField}}">
        <template #default="scope">
          {{#if (hbs_eq htmlType "checkbox")}}
          <dict-tag :options="{{dictType}}" :value="scope.row.{{tsField}} ? scope.row.{{tsField}}.split(',') : []"/>
          {{else}}
          <dict-tag :options="{{dictType}}" :value="scope.row.{{tsField}}"/>
          {{/if}}
        </template>
      </el-table-column>
      {{else}}
      <el-table-column label="{{columnComment}}" align="center" prop="{{tsField}}" />
      {{/if}}
      {{/if}}
      {{/each}}
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" 
            v-hasPermi="['{{moduleName}}:{{businessName}}:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['{{moduleName}}:{{businessName}}:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="{{businessName}}Ref" :model="form" :rules="rules" label-width="80px">
        {{#each columns}}
        {{#if isEdit}}
        {{#if (hbs_eq htmlType "input")}}
        <el-form-item label="{{columnComment}}" prop="{{tsField}}">
          <el-input v-model="form.{{tsField}}" placeholder="请输入{{columnComment}}" />
        </el-form-item>
        {{/if}}
        {{#if (hbs_eq htmlType "imageUpload")}}
        <el-form-item label="{{columnComment}}" prop="{{tsField}}">
          <image-upload v-model="form.{{tsField}}"/>
        </el-form-item>
        {{/if}}
        {{#if (hbs_eq htmlType "fileUpload")}}
        <el-form-item label="{{columnComment}}" prop="{{tsField}}">
          <file-upload v-model="form.{{tsField}}"/>
        </el-form-item>
        {{/if}}
        {{#if (hbs_eq htmlType "editor")}}
        <el-form-item label="{{columnComment}}">
          <editor v-model="form.{{tsField}}" :min-height="192"/>
        </el-form-item>
        {{/if}}
        {{#if (hbs_and (hbs_eq htmlType "select") dictType)}}
        <el-form-item label="{{columnComment}}" prop="{{tsField}}">
          <el-select v-model="form.{{tsField}}" placeholder="请选择{{columnComment}}">
            <el-option
              v-for="dict in {{dictType}}"
              :key="dict.value"
              :label="dict.label"
              {{#if (hbs_eq tsType "number")}}
              :value="parseInt(dict.value)"
              {{else}}
              :value="dict.value"
              {{/if}}
            ></el-option>
          </el-select>
        </el-form-item>
        {{/if}}
        {{#if (hbs_and (hbs_eq htmlType "select") (hbs_eq dictType))}}
        <el-form-item label="{{columnComment}}" prop="{{tsField}}">
          <el-select v-model="form.{{tsField}}" placeholder="请选择{{columnComment}}">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        {{/if}}
        {{#if (hbs_eq htmlType "checkbox" dictType)}}
        <el-form-item label="{{columnComment}}" prop="{{tsField}}">
          <el-checkbox-group v-model="form.{{tsField}}">
            <el-checkbox
              v-for="dict in {{dictType}}"
              :key="dict.value"
              :label="dict.value">
              {{dict.label}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        {{/if}}
        {{#if (hbs_eq htmlType "checkbox" (hbs_eq dictType))}}
        <el-form-item label="{{columnComment}}" prop="{{tsField}}">
          <el-checkbox-group v-model="form.{{tsField}}">
            <el-checkbox>请选择字典生成</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        {{/if}}
        {{#if (hbs_eq htmlType "radio" dictType)}}
        <el-form-item label="{{columnComment}}" prop="{{tsField}}">
          <el-radio-group v-model="form.{{tsField}}">
            <el-radio
              v-for="dict in {{dictType}}"
              :key="dict.value"
              {{#if (hbs_eq tsType "number")}}
              :label="parseInt(dict.value)"
              {{else}}
              :label="dict.value"
              {{/if}}
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        {{/if}}
        {{#if (hbs_eq htmlType "radio" (hbs_eq dictType))}}
        <el-form-item label="{{columnComment}}" prop="{{tsField}}">
          <el-radio-group v-model="form.{{tsField}}">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        {{/if}}
        {{#if (hbs_eq htmlType "datetime")}}
        <el-form-item label="{{columnComment}}" prop="{{tsField}}">
          <el-date-picker clearable
            v-model="form.{{tsField}}"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择{{columnComment}}">
          </el-date-picker>
        </el-form-item>
        {{/if}}
        {{#if (hbs_eq htmlType "textarea")}}
        <el-form-item label="{{columnComment}}" prop="{{tsField}}">
          <el-input v-model="form.{{tsField}}" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        {{/if}}
        {{/if}}
        {{/each}}
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="{{BusinessName}}">
import { list{{BusinessName}}, get{{BusinessName}}, del{{BusinessName}}, add{{BusinessName}}, update{{BusinessName}} } from "@/api/{{moduleName}}/{{businessName}}";

const { proxy } = getCurrentInstance();
{{#if dicts}}
const { {{dicts}} } = proxy.useDict({{dicts}});
{{/if}}

const {{businessName}}List = ref([]);
{{#if table.sub}}
const {{subclassName}}List = ref([]);
{{/if}}
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
{{#if table.sub}}
const checked{{subClassName}} = ref([]);
{{/if}}
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
{{#each columns}}
{{#if (hbs_and (hbs_eq htmlType "datetime") (hbs_eq queryType "BETWEEN"))}}
#set($AttrName=$tsField.substring(0,1).toUpperCase() + ${tsField.substring(1)})
const daterange{{AttrName}} = ref([]);
{{/if}}
{{/each}}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    {{#each columns}}
    {{#if query}}
    {{tsField}}: null{{#unless @last}},{{/unless}}
    {{/if}}
    {{/each}}
  },
  rules: {
    {{#each columns}}
    {{#if required}}
    {{#if (hbs_or (hbs_eq htmlType "select") (hbs_eq htmlType "radio") (hbs_eq htmlType "checkbox"))}}
    {{tsField}}: [
      { required: true, message: "{{columnComment}}不能为空", trigger: "change" }
    ]{{#unless @last}},{{/unless}}
    {{else}}
    {{tsField}}: [
      { required: true, message: "{{columnComment}}不能为空", trigger: "blur" }
    ]{{#unless @last}},{{/unless}}
    {{/if}}
    {{/if}}
    {{/each}}
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询{{functionName}}列表 */
function getList() {
  loading.value = true;
  {{#each columns}}
  {{#if (hbs_and (hbs_eq htmlType "datetime") (hbs_eq queryType "BETWEEN"))}}
  queryParams.value.params = {};
  {{break}}
  {{/if}}
  {{/each}}
  {{#each columns}}
  {{#if (hbs_and (hbs_eq htmlType "datetime") (hbs_eq queryType "BETWEEN"))}}
  #set($AttrName=$tsField.substring(0,1).toUpperCase() + ${tsField.substring(1)})
  if (null != daterange{{AttrName}} && '' != daterange{{AttrName}}) {
    queryParams.value.params["begin{{AttrName}}"] = daterange{{AttrName}}.value[0];
    queryParams.value.params["end{{AttrName}}"] = daterange{{AttrName}}.value[1];
  }
  {{/if}}
  {{/each}}
  list{{BusinessName}}(queryParams.value).then(response => {
    {{businessName}}List.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    {{#each columns}}
    {{#if (hbs_eq htmlType "checkbox")}}
    {{tsField}}: []{{#unless @last}},{{/unless}}
    {{else}}
    {{tsField}}: null{{#unless @last}},{{/unless}}
    {{/if}}
    {{/each}}
  };
  {{#if table.sub}}
  {{subclassName}}List.value = [];
  {{/if}}
  proxy.resetForm("{{businessName}}Ref");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  {{#each columns}}
  {{#if (hbs_and (hbs_eq htmlType "datetime") (hbs_eq queryType "BETWEEN"))}}
  #set($AttrName=$tsField.substring(0,1).toUpperCase() + ${tsField.substring(1)})
  daterange{{AttrName}} = [];
  {{/if}}
  {{/each}}
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.{{pkColumn.tsField}});
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加{{functionName}}";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _{{pkColumn.tsField}} = row.{{pkColumn.tsField}} || ids.value
  get{{BusinessName}}(_{{$pkColumn.tsField}}).then(response => {
    form.value = response.data;
    {{#each columns}}
    {{#if (hbs_eq htmlType "checkbox")}}
    form.value.{{tsField}} = form.value.{{tsField}}.split(",");
    {{/if}}
    {{/each}}
    {{#if table.sub}}
    {{subclassName}}List.value = response.data.{{subclassName}}List;
    {{/if}}
    open.value = true;
    title.value = "修改{{functionName}}";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["{{businessName}}Ref"].validate(valid => {
    if (valid) {
      {{#each columns}}
      {{#if (hbs_eq htmlType "checkbox")}}
      form.value.{{tsField}} = form.value.{{tsField}}.join(",");
      {{/if}}
      {{/each}}
      {{#if table.sub}}
      form.value.{{subclassName}}List = {{subclassName}}List.value;
      {{/if}}
      if (form.value.{{pkColumn.tsField}} != null) {
        update{{BusinessName}}(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        add{{BusinessName}}(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _{{pkColumn.tsField}}s = row.{{pkColumn.tsField}} || ids.value;
  proxy.$modal.confirm('是否确认删除{{functionName}}编号为"' + _{{pkColumn.tsField}}s + '"的数据项？').then(function() {
    return del{{BusinessName}}(_{{pkColumn.tsField}}s);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

{{#if table.sub}}
/** {{subTable.functionName}}序号 */
function row{{subClassName}}Index({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** {{subTable.functionName}}添加按钮操作 */
function handleAdd{{subClassName}}() {
  let obj = {};
  {{#each subTable.columns}}
  {{#if (hbs_or (hbs_eq pk true) (hbs_eq tsField subTableFkclassName))}}
  {{else if (hbs_and (hbs_eq list true) (hbs_eq htmlType "input"))}}
  obj.{{tsField}} = "";
  {{/if}}
  {{/each}}
  {{subclassName}}List.value.push(obj);
}

/** {{subTable.functionName}}删除按钮操作 */
function handleDelete{{subClassName}}() {
  if (checked{{subClassName}}.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的{{subTable.functionName}}数据");
  } else {
    const {{subclassName}}s = {{subclassName}}List.value;
    const checked{{subClassName}}s = checked{{subClassName}}.value;
    {{subclassName}}List.value = {{subclassName}}s.filter(function(item) {
      return checked{{subClassName}}s.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handle{{subClassName}}SelectionChange(selection) {
  checked{{subClassName}}.value = selection.map(item => item.index)
}

{{/if}}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('{{moduleName}}/{{businessName}}/export', {
    ...queryParams.value
  }, '{{businessName}}_#[[${new Date().getTime()}]]#.xlsx')
}

getList();
</script>
